package com.sosee.cgfw.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.sosee.cgfw.R;
import com.sosee.cgfw.adapter.FragmentAdapter;
import com.sosee.cgfw.adapter.ScheduleAdapter;
import com.sosee.cgfw.entity.JsonData;
import com.sosee.cgfw.entity.PiaoJia;
import com.sosee.cgfw.entity.PiaoJiaData;
import com.sosee.cgfw.fragment.RiLiFragment;
import com.sosee.cgfw.interfac.ScheduleInterface;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Thinkpad on 2016/2/18.
 *
 * 智能助理页面
 */
public class AssistantActivity extends FragmentActivity implements ScheduleInterface, AdapterView.OnItemClickListener {

    private List<JsonData> list;//活动日程集合
    private ListView lv;//活动列表
    private ScheduleAdapter myadapter;
    private HttpUtils httpUtils;
    private List<String> rList=new ArrayList<String>();//提醒列表
    private ViewPager vp;
    private List<Fragment> fList=new ArrayList<Fragment>();
    private FragmentAdapter fAdapter;
    private RiLiFragment f1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_assistant);
        httpUtils=new HttpUtils();
        httpUtils.configCurrentHttpCacheExpiry(10);
        initView();
        initData();
        setDay();
        initData_web();
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void initView(){
        vp= (ViewPager) findViewById(R.id.rl_rili);
        f1=new RiLiFragment();
        fList.add(f1);
        fAdapter=new FragmentAdapter(getSupportFragmentManager());
        fAdapter.setList(fList);
        vp.setAdapter(fAdapter);
        lv= (ListView) findViewById(R.id.lv);
        myadapter=new ScheduleAdapter(this);
        myadapter.setAnInterface(this);
        myadapter.setFrom(2);
        lv.setOnItemClickListener(this);
        lv.setAdapter(myadapter);


    }







    private SharedPreferences sp=null;
    //获取用户设置的提醒列表
    public void getReminList(){
        String id=sp.getString(Constans.ALARM,"");
        rList=Utils.stringToList(id, ",");
    }



    //处理返回和品牌点击事件
    public void onClick(View view){
        int id=view.getId();
        switch (id){
            case R.id.ig_fanhui:
                finish();
                break;
            case R.id.ig_shenqing:
                showPopWindow(view);
//                startActivity(new Intent(this,ApplyActivity.class));
                break;
            //邀请函
            case R.id.ll_my_picket:
                startActivity(new Intent(this, InvitationActivity.class));
                finish();
                break;
            case R.id.ll_my_yaoqing:
                startActivity(new Intent(this,ApplyActivity.class));
                finish();
                break;
        }
//
    }
    private PopupWindow pop;
    //显示下拉菜单
    public void showPopWindow(View view){
        WindowManager wm=getWindowManager();
        int w=wm.getDefaultDisplay().getWidth();
        LinearLayout layout= (LinearLayout) View.inflate(this,R.layout.pop_assistant,null);

        pop = new PopupWindow(layout, Utils.dip2px(this,126)
                , Utils.dip2px(this,65));

        layout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = layout.getMeasuredWidth();
        int popupHeight = layout.getMeasuredHeight();



        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setBackgroundDrawable(new BitmapDrawable());
        int[] location=new int[2];
        view.getLocationOnScreen(location);


        LogUtils.log_E(location[1] + "");
        LogUtils.log_E(pop.getHeight()+"");

        pop.showAtLocation(view, Gravity.NO_GRAVITY, w-Utils.dip2px(this,120), location[1]+view.getHeight()+Utils.dip2px(this,5));

    }



    public void initData(){
        sp=getSharedPreferences(Constans.ALARM,MODE_PRIVATE);
        Collections.sort(Utils.list_date);
        getReminList();
    }
    //联网获取已收藏列表
    public void getShouCang(final String date){
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.URL_SHOUCANG+Constans.userID + "&showID=-1", new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    JSONObject obj = new JSONObject(responseInfo.result);
                    String slist = obj.getString("data");
                    Utils.list_shoucang.clear();
                    Utils.list_shoucang.addAll(Utils.stringToList(slist, ","));
                    getList(date, null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast(getString(R.string.internet_error));
            }
        });

    }
    private MyCollection collection=new MyCollection();

    public class MyCollection implements Comparator<JsonData> {

        @Override
        public int compare(JsonData lhs, JsonData rhs) {
            String time1=lhs.getData().getStart_time();
            String time2=rhs.getData().getStart_time();

            return time1.compareTo(time2);
        }
    }



    //联网获取活动日程
    public void getList(String time,String location){
        String url=Constans.URL_SCHEDULE+"?date="+time;
        if(location!=null&&!"".equals(location)){
            url=url+"&loc="+location;
        }

        httpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {


            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                list=new ArrayList<JsonData>();
                //获取网络数据 刷新listview
                List<JsonData> temList=new ArrayList<JsonData>();
                temList = Utils.getSchedule(responseInfo.result);

                for (int i=0;i<temList.size();i++){
                    boolean isRemind=rList.contains(temList.get(i).getData().getID());
                    boolean isShouCang=Utils.list_shoucang.contains(temList.get(i).getData().getID());
                    if(isShouCang||isRemind){
                        String text="";
                        if(!isRemind&&isShouCang){
                            text="收藏";
                        }else if(isRemind&&isShouCang){
                            text="收藏并提醒";
                        }else{
                            text="提醒";
                        }
                        myadapter.setRemind(text);

                        list.add(temList.get(i));

                    }
                }
                Collections.sort(list, collection);
                myadapter.setList(list);
                myadapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast("" + e.getMessage());

            }
        });
    }

    //展开菜单按钮点击事件
    @Override
    public void onZhankaiClick(int position,boolean zhanKai) {
        if(position<1000){
            if(zhanKai){
                Utils.list_menu.add(position+"");
                myadapter.notifyDataSetChanged();
            }else{
                Utils.list_menu.remove(position+"");
                myadapter.notifyDataSetChanged();
            }
        }else {
            getShouCang(date);
        }


    }
    //item点击事件
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent=new Intent(this,ScheduleDetailActivity.class);
        JsonData data= (JsonData) adapterView.getItemAtPosition(i);
        intent.putExtra("from",2);
        intent.putExtra("detail", data);
        startActivity(intent);
        finish();
    }

    //清除菜单展开记录
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清楚数据
        Utils.list_menu.clear();
    }
    private String date="2016-05-14";//日期
    private String[] dates=new String[]{"2016-05-14","2016-05-15","2016-05-16","2016-05-17","2016-05-18","2016-05-19","2016-05-20"};

    //日历点击事件
    public void click(View view){
        int id=view.getId();
        int position=0;
        switch (id){
            case R.id.ig_day25:
                position=0;
                break;
            //查询25
//            case R.id.ig_day25:
//                position=0;
//                break;
            case R.id.ig_day26:
                position=1;
                break;
            case R.id.ig_day27:
                position=2;
                break;
            case R.id.ig_day28:
                position=3;
                break;
            case R.id.ig_day29:
                position=4;
                break;
            case R.id.ig_day30:
                position=5;
                break;
            case R.id.ig_day31:
                position=6;
                break;
//            case R.id.ig_day24:
//                position=7;
//                break;
        }
        doClick(position,dates[position]);
    }
    public void setDay(){
        switch (Utils.day){
                //查询25
                case 0:
                    doClick(0,dates[0]);
                    break;
                case 1:
                    doClick(1,dates[1]);
                    break;
                case 2:
                    doClick(2,dates[2]);
                    break;
                case 3:
                    doClick(3,dates[3]);
                    break;
                case 4:
                    doClick(4,dates[4]);
                    break;
                case 5:
                    doClick(5,dates[5]);
                    break;
                case 6:
                    doClick(6,dates[6]);
                    break;
                case 7:
                    doClick(7,dates[7]);
                    break;
            }

    }
    public void doClick(int position,String date){
        LogUtils.log_E("测试智能助力："+position);
        Utils.day=position;
        f1.doClick(position, date);
        getShouCang(date);
    }
    public void initData_web(){
        httpUtils.configCurrentHttpCacheExpiry(1000 * 1);
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.PIAO_URL + Constans.userID, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    LogUtils.log_E("测试票夹数据："+responseInfo.result);
                    JSONObject jsonObject = new JSONObject(responseInfo.result);
                    String status = jsonObject.getString("status");

                    if ("success".equals(status)) {
                        String result = jsonObject.getString("result");
                        List<PiaoJia> list = com.alibaba.fastjson.JSONArray.parseArray(result, PiaoJia.class);
                        initUI(list);
                    } else {
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    LogUtils.log_E("票夹解析json" + e.getMessage());
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast("网络异常");
            }
        });
    }

    public void initUI(List<PiaoJia> list){
        Utils.piaoJiaList.clear();
        Utils.shenQingList.clear();
        for (int i=0;i<list.size();i++){
            PiaoJiaData pdata=list.get(i).getData();
            String status=pdata.getStatus();
            String show=pdata.getShow().get(0);
            if(show!=null&&show.length()>10){
                if(status!=null){
                    if(status.equals("1")||status.equals("4")){
                        if(status.equals("1")){
                            Utils.shenQingList.add(pdata);
                        }
                    }else if(status.equals("2")||status.equals("3")){
                        Utils.piaoJiaList.add(pdata);
                    }else if(status.equals("5")||status.equals("6")){
                        Utils.shenQingList.add(pdata);
                    }
                }
            }

        }
    }




    //默认显示最近的时间
    public void showDay(){

        Calendar ca = Calendar.getInstance();
        int year = ca.get(Calendar.YEAR);//获取年份
        int month=ca.get(Calendar.MONTH)+1;//获取月份
        int day=ca.get(Calendar.DATE);//获取日
        String mo="";
        String da="";
        if(month<10){
            mo="0"+month;
        }else{
            mo=month+"";
        }
        if(day<10){
            da="0"+day;
        }else{
            da=day+"";
        }
        LogUtils.log_E(year + "-" + mo + "-" + da);
        String date=year+"-"+mo+"-"+da;
        int position=Utils.list_date.indexOf(date);
        if(position>-1){
            Utils.day=position;
        }else{
            if(date.compareTo(Utils.list_date.get(0))<=0){
                Utils.day=0;
            }else{
                if (date.compareTo(Utils.list_date.get(Utils.list_date.size()-1))>0){
                    Utils.day=Utils.list_date.size()-1;
                }
            }
        }
    }
























}
